package com.wn.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wn.auth.JWTUtil;
import com.wn.common.Const;
import com.wn.common.PageParam;
import com.wn.mapper.*;
import com.wn.ov.DepartmentUserOv;
import com.wn.ov.FormOv;
import com.wn.ov.PatientOv;
import com.wn.ov.UserOv;
import com.wn.pojo.*;
import com.wn.resopnse.ResponseCode;
import com.wn.resopnse.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.util.List;

/**
 * @BelongsProject: his
 * @BelongsPackage: com.wn.service
 * @Author: faker
 * @CreateTime: 2020-10-26 11:39
 * @Description: 用户模块业务处理层
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    //预约表
    @Autowired
    private AppointmentMapper appointmentMapper;
    //科室表
    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private CostMapper costMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PatientDetailMapper patientDetailMapper;

    //根据id查询用户
    public User getUserById(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    //查询护士列表
    public List<User> getNurseList(){
        List<User> nurseList = userMapper.getNurseList();
        return nurseList;
    }

    /**
     * 用户登录
     *
     * @param loginEntity
     * @return
     */
    public ServerResponse login(UserOv loginEntity) {
        UserOv login = userMapper.login(loginEntity);
        Role role = roleMapper.selectByPrimaryKey(login.getRoleId() + "");
        UserOv userOv = new UserOv();
        userOv.setId(login.getId());
        userOv.setRoleId(login.getRoleId());
        userOv.setUserName(login.getUserName());
        userOv.setRoleSign(role.getRoleSign());
        userOv.setRoleName(role.getRoleName());
        if (login != null) {
            String token = JWTUtil.generateToken(userOv, Const.PRIVATE_KEY, 30);
            return new ServerResponse(ResponseCode.SUCCESS, token, "登录成功");
        } else {

            return new ServerResponse(ResponseCode.ERROR, "账号或密码错误");
        }
    }



    /**
     * 提交预约信息前的数据准备
     * 科室的信息
     */
    public List<Department> departmentMsg() {
        //科室信息列表
        return departmentMapper.queryList();


    }

    /**
     * 提交预约信息前的数据准备,医生的信息
     * @param postId
     */
    public List<User> doctorMsg(Integer postId) {
        return userMapper.doctorList(postId);

    }

    /**
     * 用户注册
     *
     * @param user
     */
    public ServerResponse register(User user) {
        User register = new User();
        register.setAccount(user.getAccount());
        User user1 = userMapper.searchSomeByPage(register);
        if (StringUtils.isEmpty(user1)) {
            userMapper.insertSelective(user);
            return new ServerResponse(ResponseCode.SUCCESS, "注册成功");
        } else {
            return new ServerResponse(ResponseCode.ERROR, "用户名已存在，请重新注册");
        }
    }

    /**
     * 用户预约
     */
    public ServerResponse addAppoint(Appointment appointment) {
        int i = appointmentMapper.insertSelective(appointment);
        PatientDetail patientDetail=new PatientDetail();
        if (i > 0) {
            //预约成功，生成病人详情

            patientDetail.setPatientId(appointment.getPatientId());
            patientDetail.setDepartmentId(appointment.getDepartmentId());
            patientDetail.setDoctorId(appointment.getDoctorUserId());
            patientDetailMapper.insertSelective(patientDetail);
            return new ServerResponse(ResponseCode.SUCCESS, "已预约，正在审核中");

        } else {
            return new ServerResponse(ResponseCode.ERROR, "预约失败，请重新预约");
        }
    }

//    //修改预约状态
//    public ServerResponse updateAppoint(Appointment appointment,Integer id){
//         appointment.setStatus(1);
//        int i = appointmentMapper.updateByPrimaryKeySelective(appointment);
//        if(i!=0){
//            //根据id来查询
//            Appointment appointment1 = appointmentMapper.selectByPrimaryKey(appointment.getId());
//
//            Cost cost = new Cost();
//            cost.setCreateUserId(id);
//            cost.setTotalMoney(new BigDecimal(0));
//            cost.setPatientId(appointment1.getPatientId());
//            costMapper.insertSelective(cost);
//            return new ServerResponse(ResponseCode.SUCCESS,"预约成功");
//        }else {
//            return new ServerResponse(ResponseCode.ERROR,"没有此项记录");
//        }
//    }


    //getUserInfo
    public ServerResponse getUserInfo(Integer id){
        //通过userId来获取前端需要的信息
        UserOv userOv = userMapper.getUserOvByUserId(id);
        userOv.setPassword("");
        if(StringUtils.isEmpty(userOv)){
            return new ServerResponse(ResponseCode.ERROR,"获取失败");
        }else{
            return new ServerResponse(ResponseCode.SUCCESS,userOv,"获取成功");
        }
    }


    public ServerResponse getAppointment(Integer doctorId, PageParam pageParam) {
        if(!StringUtils.isEmpty(pageParam.getSuperSearchKeyWord())){
            //执行高级检索
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            //排序
            for(int i=0;i<pageParam.getOrderParams().length;i++){
                PageHelper.orderBy(pageParam.getOrderParams()[i]);
            }
            List<FormOv> ovList=appointmentMapper.superSearch(pageParam.getSuperSearchKeyWord(),doctorId);
            PageInfo<FormOv> ovPageInfo = new PageInfo<FormOv>(ovList);
            return new ServerResponse(ResponseCode.SUCCESS,ovPageInfo,"");

        }else{
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            //排序
            for(int i=0;i<pageParam.getOrderParams().length;i++){
                PageHelper.orderBy(pageParam.getOrderParams()[i]);
            }
            List<FormOv> ovList = appointmentMapper.selectByDoctor(doctorId);
            PageInfo<FormOv> ovPageInfo = new PageInfo<FormOv>(ovList);

            return new ServerResponse(ResponseCode.SUCCESS,ovPageInfo,"");
        }
    }



    //审核预约
    public ServerResponse updateAppointment(Appointment appointment) {
        appointment.setStatus(1);
        int i = appointmentMapper.updateAppointment(appointment);
        if (i>0){
            PatientDetail detail = patientDetailMapper.selectByPatientId(appointment.getPatientId());
            if (StringUtils.isEmpty(detail)){
                //生成病人详情
                PatientDetail patientDetail = new PatientDetail();
                patientDetail.setPatientId(appointment.getPatientId());
                patientDetail.setDoctorId(appointment.getDoctorUserId());
                patientDetail.setDepartmentId(appointment.getDepartmentId());
                patientDetailMapper.insertSelective(patientDetail);
            }
            return new ServerResponse(ResponseCode.SUCCESS,"审核成功");
        }
        return new ServerResponse(ResponseCode.ERROR,"审核失败");
    }
    //撤销审核
    public ServerResponse updateAppointmentCancel(Appointment appointment) {
        appointment.setStatus(0);
        int i = appointmentMapper.updateAppointmentCancel(appointment);
        if (i>0){
            PatientDetail detail = patientDetailMapper.selectByPatientIdAndStatus(appointment.getPatientId());
           if(!StringUtils.isEmpty(detail)){
               patientDetailMapper.deleteByPrimaryKey(detail.getId());
           }
            return new ServerResponse(ResponseCode.SUCCESS,"撤销成功");
        }
        return new ServerResponse(ResponseCode.ERROR,"撤销失败");
    }

    public ServerResponse deleteAppointment(Appointment appointment) {
        appointmentMapper.deleteByPrimaryKey(appointment.getId());
        return new ServerResponse(ResponseCode.SUCCESS,"删除成功");
    }

    //修改用户的信息
    public ServerResponse updatePatient(PatientOv patientOv){
        User user = new User();
        user.setId(patientOv.getId());
        user.setRealName(patientOv.getRealName());
        user.setAge(patientOv.getAge());
        user.setGender(patientOv.getGender());
        user.setTelephone(patientOv.getTelephone());


        int i = userMapper.updateByPrimaryKeySelective(user);
        if(i ==0){
            return new ServerResponse(ResponseCode.ERROR,"失败");
        }else{
            return new ServerResponse(ResponseCode.SUCCESS,"成功");
        }
    }

    //登录后首页的个人信息展示
    public ServerResponse getUserMsgById(Integer id){
        DepartmentUserOv userMsgById = userMapper.getUserMsgById(id);
        return new ServerResponse(ResponseCode.SUCCESS,userMsgById);
    }

    public List<User> doctorMsgByCurrent(UserOv user) {
        return userMapper.selectByCurrentDept(user.getId());
    }
}
